package gao.xiaolei.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * 用于读取指定位置的xml文件的信息
 * 
 * @throws IOException
 * 
 */
public class ReadFile {
	// 读取eureka上服务的名字
	public static List<String> readServiceName(String url) throws ParserConfigurationException, SAXException, IOException {
		// 读取外部配置参数
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(url);
		// 读取xml内部节点集合
		NodeList apps = doc.getElementsByTagName("application");
		List<String> names=new ArrayList<String>(apps.getLength());
		for (int i = 0; i < apps.getLength(); i++) {
			Element node = (Element) apps.item(i);
			names.add(node.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
		}
		return names;
	}

	// 读取eureka上对应服务地址Ip
	public static List<String> readServiceIp(String url, String name)
			throws ParserConfigurationException, SAXException, IOException {
		// 读取外部配置参数
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(url);
		// 读取xml内部节点集合
		int i, j;
		List<String> ips=null;
		NodeList instances = null;
		NodeList apps = doc.getElementsByTagName("application");
		for (i = 0; i < apps.getLength(); i++) {
			Element app = (Element) apps.item(i);
			if (app.getElementsByTagName("name").item(0).getFirstChild().getNodeValue().equals(name)) {
				instances = app.getElementsByTagName("instance");
				ips=new ArrayList<String>(instances.getLength());
				for (j = 0; j < instances.getLength(); j++) {
					Element instance = (Element) instances.item(j);
					ips.add(instance.getElementsByTagName("homePageUrl").item(0).getFirstChild().getNodeValue());
				}
				break;
			}
		}
		return ips;
	}
}
